package com.sh.learn.ibeifeng.webservice.axis;

import java.util.StringTokenizer;

import org.apache.axis.AxisFault;
import org.apache.axis.Handler;
import org.apache.axis.MessageContext;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.i18n.Messages;
import org.apache.axis.security.AuthenticatedUser;
import org.apache.axis.security.SecurityProvider;

public class AuthorizationHandler extends BasicHandler{

    public void invoke(MessageContext msgContext) throws AxisFault {
		// 得到认证用户
	    AuthenticatedUser authUser = (AuthenticatedUser)msgContext.getProperty("authenticatedUser");
	    if(authUser == null){
	    	throw new AxisFault("Server no user", Messages.getMessage("need user"), null, null);
	    }
	    // 获得用户名
	    String userid = authUser.getName();
	    System.out.println(userid);
	    // 获得当前服务
	    Handler service = msgContext.getService();
	    if(service == null){
	    	throw new AxisFault(Messages.getMessage("need service"));
	    }
	    // 获得可访问角色信息
	    String allowedRoles = (String)service.getOption("allowedRoles");
	    if(allowedRoles == null){
	    	return; // 不需要验证
	    }
	    // 安全权限对象
	    SecurityProvider provider = (SecurityProvider)msgContext.getProperty("securityProvider");
	    if(provider == null){
	    	throw new AxisFault(Messages.getMessage("need provider"));
	    }
	    // 比对
	    for(StringTokenizer st = new StringTokenizer(allowedRoles, ","); st.hasMoreTokens();){
	    	String role = st.nextToken();
	    	if(provider.userMatches(authUser, role)){
	    		System.out.println("ok");
	    		return; // 通过验证
	    	}
	    }
	    // 没有通过比对
	    throw new AxisFault(Messages.getMessage("server unauthenticated"));
    }

	
}
